{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "42dca2db",
   "metadata": {},
   "source": [
    "# 创建工具"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8b6d2533",
   "metadata": {},
   "source": [
    "创建工具的最简单方法是使用 @tool 装饰器。默认情况下，函数的文档字符串成为工具的描述，帮助模型了解何时使用它："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "49e19387",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.tools import tool\n",
    "\n",
    "@tool\n",
    "def search_database(query: str, limit: int = 10) -> str:\n",
    "    \"\"\"Search the customer database for records matching the query.\n",
    "\n",
    "    Args:\n",
    "        query: Search terms to look for\n",
    "        limit: Maximum number of results to return\n",
    "    \"\"\"\n",
    "    return f\"Found {limit} results for '{query}'\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "897897b0",
   "metadata": {},
   "source": [
    "# jsonschema模式"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "02393d38",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 这个jsonschema非常重要。是决定大模型选择工具调用准确的因素\n",
    "weather_schema = {\n",
    "    \"type\": \"object\",  # 声明输入参数整体是一个对象（字典）\n",
    "    \"properties\": {    # 定义对象中允许的参数及各自规则\n",
    "        \"location\": {\"type\": \"string\"},  # location必须是字符串（如城市名）\n",
    "        \"units\": {\"type\": \"string\"},     # units必须是字符串（如\"celsius\"或\"fahrenheit\"）\n",
    "        \"include_forecast\": {\"type\": \"boolean\"}  # include_forecast必须是布尔值（True/False）\n",
    "    },\n",
    "    \"required\": [\"location\", \"units\", \"include_forecast\"]  # 必须传入的参数（缺一不可）\n",
    "}\n",
    "\n",
    "@tool(args_schema=weather_schema)\n",
    "def get_weather(location: str, units: str = \"celsius\", include_forecast: bool = False) -> str:\n",
    "    \"\"\"Get current weather and optional forecast.\"\"\"\n",
    "    temp = 22 if units == \"celsius\" else 72\n",
    "    result = f\"Current weather in {location}: {temp} degrees {units[0].upper()}\"\n",
    "    if include_forecast:\n",
    "        result += \"\\nNext 5 days: Sunny\"\n",
    "    return result"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5595b6ec",
   "metadata": {},
   "source": [
    "# pydantic模式"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d1c074b1",
   "metadata": {},
   "outputs": [],
   "source": [
    "from pydantic import BaseModel, Field\n",
    "from typing import Literal\n",
    "\n",
    "class WeatherInput(BaseModel):\n",
    "    \"\"\"Input for weather queries.\"\"\"\n",
    "    location: str = Field(description=\"City name or coordinates\")\n",
    "    units: Literal[\"celsius\", \"fahrenheit\"] = Field(\n",
    "        default=\"celsius\",\n",
    "        description=\"Temperature unit preference\"\n",
    "    )\n",
    "    include_forecast: bool = Field(\n",
    "        default=False,\n",
    "        description=\"Include 5-day forecast\"\n",
    "    )\n",
    "\n",
    "@tool(args_schema=WeatherInput)\n",
    "def get_weather(location: str, units: str = \"celsius\", include_forecast: bool = False) -> str:\n",
    "    \"\"\"Get current weather and optional forecast.\"\"\"\n",
    "    temp = 22 if units == \"celsius\" else 72\n",
    "    result = f\"Current weather in {location}: {temp} degrees {units[0].upper()}\"\n",
    "    if include_forecast:\n",
    "        result += \"\\nNext 5 days: Sunny\"\n",
    "    return result"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "langchain-course (3.10.12)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
